import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators'
import {getToken, removeToken, setToken} from '@/utils/storage'
import {resetRouter} from '@/router/router'
import {TagsViewModule} from './tags-view'
import store from '@/store/store'

export interface IUserState {
    token: string
    name: string
    avatar: string
    introduction: string
    refreshStatus: string[]
    email: string
}

@Module({dynamic: true, store, name: 'user'})
class User extends VuexModule implements IUserState {
    public token = getToken() || '';
    public name = '';
    public avatar = '';
    public introduction = '';
    public refreshStatus: string[] = [];
    public email = '';

    @Mutation
    private SET_TOKEN(token: string) {
        this.token = token
    }

    @Mutation
    private SET_NAME(name: string) {
        this.name = name
    }

    @Mutation
    private SET_AVATAR(avatar: string) {
        this.avatar = avatar
    }

    @Mutation
    private SET_INTRODUCTION(introduction: string) {
        this.introduction = introduction
    }

    @Mutation
    private SET_ROLES(refreshStatus: string[]) {
        this.refreshStatus = refreshStatus
    }

    @Mutation
    private SET_EMAIL(email: string) {
        this.email = email
    }

    @Action
    public Login(token: any) {
        // let { username, password } = userInfo
        // username = username.trim()
        // const { data } = await login({ username, password })
        this.SET_TOKEN(token);
    }

    @Action
    public ResetToken() {
        removeToken();
        this.SET_TOKEN('');
        this.SET_ROLES([]);
    }

    @Action
    public async setStatus() {
        this.SET_ROLES(["shauxin", "shuaxin"]);
        this.SET_NAME("name");
        this.SET_AVATAR("avatar");
        this.SET_INTRODUCTION("introduction");
        this.SET_EMAIL("email");
    }

    @Action
    public async ChangeRoles(role: string) {
        // Dynamically modify permissions
        const token = role + '-token';
        this.SET_TOKEN(token);
        setToken(token);
        await this.setStatus();
        resetRouter();
        // Generate dynamic accessible routes based on roles
        // PermissionModule.setRouter(this.roles)
        // Add generated routes
        // router.addRoutes(PermissionModule.dynamicRoutes)
        // Reset visited views and cached views
        TagsViewModule.delAllViews()
    }

    @Action
    public async LogOut() {
        this.SET_ROLES([]);
    }
}

export const UserModule = getModule(User)
